<?php

class Agents extends CI_Controller {

    public function __construct() {
        parent::__construct();
        $this->load->model('Magents');
        $this->load->library('session');
        $this->load->library('form_validation');
        $this->load->library('encrypt');
        $this->load->model('mmaster');
        $this->load->model('mglobal');
    }

    ########################################################################
    ########################################################################
    
   	function is_logged_in(){
		$is_logged_in = $this->session->userdata('is_logged_in');
		if(!isset($is_logged_in) || $is_logged_in != true)
		{
			redirect(base_url() .'index.php/login');
		}
	}

function agents( $param1="", $param2="", $param3="" )
	{
		$data = $this->initializeArray( 'agent' );
		$arr = array( 'a_status', 'identity', 'o_location', 'a_type', 'b_focus' );
		
		if ($param1!="")
            {$fillData = $this->fillData( $arr, 'direct sales' );
          	$data = array_merge( $data, $fillData );
	}
		
		$data[ 'agent_id' ] ="";// $this->magents->generateAgentID();
		$result = '';
		$pic = '';
	//	$data['user_group_id']=$this->mmaster->getUserRole();
        //print_r ($data['user_group_id'][0]['user_group_id']);
      
        
		if( $param1 == "update" || $param1 == "approve" )
		{
		  
			$result = $this->magents->getAgents( "", $param2 );
           // $result2 = $this->magents->getUnapprovedAgents( $param2 );
		} //else
        //{
            
        //}
        
		
		if( $param1 == "bank" )
		{
			$bankData = $this->bank( $param2, $param3, 'agent' );
			$data = array_merge( $data, $bankData );
		}
		else if( $param1 == "update" )
		{
			$pic = $this->magents->getPIC( $param2 );
			$pic2 = $this->magents->getUnapprovedPIC( $param2 );
			if( $result != null )
			{
				$data[ 'agent_name' ] = $result->agent_name;
				$data[ 'agent_status' ] = $result->agent_status;
				$data[ 'agent_address' ] = $result->agent_address;
				$data[ 'agent_city' ] = $result->agent_city;
				$data[ 'agent_province' ] = $result->agent_province_id;
				$data[ 'agent_id' ] = $result->agent_id;
				$data[ 'agent_zip_code' ] = $result->agent_zip_code;
				$data[ 'agent_phone_no' ] = $result->agent_phone_no;
				$data[ 'agent_mdn_evo' ] = $result->agent_mdn_evo; 
				$data[ 'maintain_name' ] = $this->mmaster->getMaintainName( $result->territory_id , 'direct sales');
				$data[ 'agent_website' ] = $result->agent_website; 
				$data[ 'is_school' ] = $result->is_agent_a_school; 
				$data[ 'image' ] = $result->image_path;
				$data['agent_selling_type']=$result->agent_selling_type;
				if( $data[ 'is_school' ] == true )
				{
					
					$school = $this->magents->getAgentSchool( $param2 );
					$data[ 'majority_num' ] = $school->school_number_of_majority;
					$data[ 'faculty_num' ] = $school->school_number_of_faculty;
					$data[ 'student_num' ] = $school->school_number_of_student;
					$data[ 'teacher_num' ] = $school->school_number_of_teacher;
				}
				
				$data[ 'employee_num' ] = $result->agent_number_of_employee; 
				$data[ 'agent_location' ] = $result->agent_location; 
				$data[ 'agent_type' ] = $result->agent_type; 
				$data[ 'agent_business_focus' ] = $result->agent_business_focus; 
                
               /**
 *  $data['old'][ 'agent_name' ] = $result->agent_name;
 * 				$data['old'][ 'agent_status' ] = $result->agent_status;
 * 				$data['old'][ 'agent_address' ] = $result->agent_address;
 * 				$data['old'][ 'agent_city' ] = $result->agent_city;
 * 				$data['old'][ 'agent_province' ] = $result->agent_province_id;
 * 				$data['old'][ 'agent_id' ] = $result->agent_id;
 * 				$data['old'][ 'agent_zip_code' ] = $result->agent_zip_code;
 * 				$data['old'][ 'agent_phone_no' ] = $result->agent_phone_no;
 * 				$data['old'][ 'agent_mdn_evo' ] = $result->agent_mdn_evo; 
 * 				$data['old'][ 'maintain_name' ] = $this->mmaster->getMaintainName( $result->territory_id , 'direct sales'); 
 * 				$data['old'][ 'agent_website' ] = $result->agent_website; 
 * 				$data['old'][ 'is_school' ] = $result->is_agent_a_school; 
 * 				$data['old'][ 'image' ] = $result->image_path;
 * 				$data['old']['agent_selling_type']=$result->agent_selling_type;
 * 				if( $data[ 'is_school' ] == true )
 * 				{
 * 					
 * 					$school = $this->magents->getAgentSchool( $param2 );
 * 					$data['old'][ 'majority_num' ] = $school->school_number_of_majority;
 * 					$data['old'][ 'faculty_num' ] = $school->school_number_of_faculty;
 * 					$data['old'][ 'student_num' ] = $school->school_number_of_student;
 * 					$data['old'][ 'teacher_num' ] = $school->school_number_of_teacher;
 * 				}
 * 				
 * 				$data['old'][ 'employee_num' ] = $result->agent_number_of_employee; 
 * 				$data['old'][ 'agent_location' ] = $result->agent_location; 
 * 				$data['old'][ 'agent_type' ] = $result->agent_type; 
 * 				$data['old'][ 'agent_business_focus' ] = $result->agent_business_focus; 
 *                 
 */
                
                
			}
			
			if( $pic != null )
			{
				$data[ 'pic_name' ] = $pic->pic_name;
				$data[ 'pic_phone' ] = $pic->pic_phone_no;
				$data[ 'pic_address' ] = $pic->pic_address;
				$data[ 'pic_city' ] = $pic->pic_city;
				$data[ 'pic_province' ] = $pic->pic_province_id;
				$data[ 'pic_zip_code' ] = $pic->pic_zip_code;
				$data[ 'pic_identity_type' ] = $pic->pic_identity_type;
				$data[ 'pic_identity_no' ] = $pic->pic_identity_no;
				$data[ 'pic_birth_place' ] = $pic->pic_birth_place;
				$data[ 'pic_birth_date' ] = $pic->pic_birth_date;
				$data[ 'pic_job_position' ] = $pic->pic_job_position;
				$data[ 'pic_smartfren_no' ] = $pic->pic_smartfren_no;
				$data[ 'pic_mobile_no' ] = $pic->pic_mobile_no;
				$data[ 'pic_email' ] = $pic->pic_email;
                
/**
 *                 
 *                 $data['old'][ 'pic_name' ] = $pic->pic_name;
 * 				$data['old'][ 'pic_phone' ] = $pic->pic_phone_no;
 * 				$data['old'][ 'pic_address' ] = $pic->pic_address;
 * 				$data['old'][ 'pic_city' ] = $pic->pic_city;
 * 				$data['old'][ 'pic_province' ] = $pic->pic_province_id;
 * 				$data['old'][ 'pic_zip_code' ] = $pic->pic_zip_code;
 * 				$data['old'][ 'pic_identity_type' ] = $pic->pic_identity_type;
 * 				$data['old'][ 'pic_identity_no' ] = $pic->pic_identity_no;
 * 				$data['old'][ 'pic_birth_place' ] = $pic->pic_birth_place;
 * 				$data['old'][ 'pic_birth_date' ] = $pic->pic_birth_date;
 * 				$data['old'][ 'pic_job_position' ] = $pic->pic_job_position;
 * 				$data['old'][ 'pic_smartfren_no' ] = $pic->pic_smartfren_no;
 * 				$data['old'][ 'pic_mobile_no' ] = $pic->pic_mobile_no;
 * 				$data['old'][ 'pic_email' ] = $pic->pic_email;*/
			} else {
			 $data[ 'pic_name' ] = "";
				$data[ 'pic_phone' ] = "";
				$data[ 'pic_address' ] = "";
				$data[ 'pic_city' ] = "";
				$data[ 'pic_province' ] = "";
				$data[ 'pic_zip_code' ] ="";
				$data[ 'pic_identity_type' ] = "";
				$data[ 'pic_identity_no' ] ="";
				$data[ 'pic_birth_place' ] = "";
				$data[ 'pic_birth_date' ] = "";
				$data[ 'pic_job_position' ] = "";
				$data[ 'pic_smartfren_no' ] = "";
				$data[ 'pic_mobile_no' ] = "";
				$data[ 'pic_email' ] = "";
             
			}
		}
        $registered[]=' ';
        $edit[]=' ';
        $new[]=' ';
        $user_role=$this->mmaster->checkUserRole(56);
        if($user_role['menu_add']){
            
        }
        if($user_role['menu_view']){
            $registered[]='<a class="viewBtnNew" href="'.base_url().'index.php/act_agents/view/">View</a>';
    		$edit[]='<a class="viewBtnNew" href="'.base_url().'index.php/act_agents/viewDiff/">View</a>';
            $new[]='<a class="viewBtnNew" href="'.base_url().'index.php/act_agents/view/">View</a>';   
        }
        if($user_role['menu_edit']){
            $registered[]='<a class="updateBtnNew" href="'.base_url().'index.php/master/agents/update/">Edit</a>';
    		$edit[]='<a class="updateBtnNew" href="'.base_url().'index.php/master/agents/update/">Edit</a>';
            $new[]='<a class="updateBtnNew" href="'.base_url().'index.php/master/agents/update/">Edit</a>'; 
        }
        if($user_role['menu_delete']){
            $registered[]='<a class="deleteBtn" href="'.base_url().'index.php/act_agents/delete/primer/">Delete</a>';
    	}
        if($user_role['menu_approve']){
            $edit[]='<a class="approveBtnNew" href="'.base_url().'index.php/master/agents/approve/">Approve</a>';
            $new[]='<a class="approveBtnNew" href="'.base_url().'index.php/master/agents/approve/">Approve</a>'; 
        }
        if($user_role['menu_reject']){
            $edit[]='<a class="rejectBtnNew" href="'.base_url().'index.php/act_agents/delete/temp/">Reject</a>';
            $new[]='<a class="rejectBtnNew" href="'.base_url().'index.php/act_agents/delete/primer/">Reject</a>'; 
        }
        // inisialisasi dan validasi form
        $data['menu']['registered']=implode(" | ",$registered);
        $data['menu']['edit']=implode(" | ",$edit);
        $data['menu']['new']=implode(" | ",$new);
        if($data['menu']['registered']==null){
            $data['menu']['registered']='';
        }
        if($data['menu']['edit']==null){
            $data['menu']['edit']='';
        }
        if($data['menu']['new']==null){
            $data['menu']['new']='';
        }
		$this->form_validation->set_rules('agent_selling_type', 'Tipe Penjualan', 'required');
		$this->form_validation->set_rules('agent_name', 'Nama Agen/Lokasi', 'required');
		$this->form_validation->set_rules('agent_address', 'Alamat Agen/Lokasi', 'required');
		$this->form_validation->set_rules('agent_city', 'Kota', 'required');
		$this->form_validation->set_rules('agent_type', 'Tipe Agen', 'required');
		//$this->form_validation->set_rules('pic_name', 'Nama PIC', 'required');
		           
		if( $param1 == 'approve' )
		{
			$this->magents->updateAgents( $param1, $result->agent_id, $result->territory_id, $result->is_agent_a_school );
			$this->session->set_flashdata('message', 'Data sudah disetujui');
			redirect(base_url()."index.php/master/agents");
		}
		
		if ($this->form_validation->run() != FALSE)
		{
			$message = '';
			if( $param1 == 'update' )
			{
			 $a=	$this->magents->updateAgents( $param1, $result->agent_id, $result->territory_id, $result->is_agent_a_school );
				$message = $a;//'Data berhasil diubah'.$a.'kk';
			}
			else
			{
				//$data[ 'agent_id' ] = $this->magents->generateAgentID();
				$this->magents->saveAgents();
				$message = "Data No ".$data['agent_id']." berhasil dimasukkan";
			}
			$this->session->set_flashdata('message', $message);
			redirect(base_url()."index.php/master/agents");
		}			
		
		$this->load->view($data['template'],$data);
	}
	
	
	/* function initializeArray
	 * @author: Willy Halim Dinata
	 * @param:
	 *		$name => nama entitas
	 */
	private function initializeArray( $name )
	{
		if( $name == 'agent' )
		{
			$data['template'] = "shell/smooth";
			$data['main_view'] = 'f-agents';
			$data[ 'agent_name' ] = null;
			$data[ 'agent_address' ] = null;
			$data[ 'agent_city' ] = null;
			$data[ 'agent_province' ] = null;
			$data[ 'agent_id' ] = null;
			$data[ 'agent_zip_code' ] = null;
			$data[ 'agent_phone_no' ] = null;
			$data[ 'agent_mdn_evo' ] = null;
			$data[ 'image' ] = null;
			$data[ 'maintain_name' ] = null; 
			$data[ 'is_school' ] = null; 	
			$data[ 'majority_num' ] = null;
			$data[ 'faculty_num' ] = null;
			$data[ 'student_num' ] = null;
			$data[ 'teacher_num' ] = null;		
			$data[ 'employee_num' ] = null; 
			$data[ 'agent_location' ] = null; 
			$data[ 'agent_type' ] = null; 
			$data[ 'agent_selling_type' ] = null;  // yaddi
			$data[ 'agent_business_focus' ] = null; 
			$data[ 'agent_website' ] = null; 
			$data[ 'pic_name' ] = null;
			$data[ 'pic_phone' ] = null;
			$data[ 'pic_address' ] = null;
			$data[ 'pic_city' ] = null;
			$data[ 'pic_province' ] = null;
			$data[ 'pic_zip_code' ] = null;
			$data[ 'pic_identity_type' ] = null;
			$data[ 'pic_identity_no' ] = null;
			$data[ 'pic_birth_place' ] = null;
			$data[ 'pic_birth_date' ] = null;
			$data[ 'pic_job_position' ] = null;
			$data[ 'pic_smartfren_no' ] = null;
			$data[ 'pic_mobile_no' ] = null;
			$data[ 'pic_email' ] = null;
		}
		else if( $name == "outlet" )
		{
			$data['template'] = "shell/smooth";
			$data['main_view'] = "f-outlets";
			$data[ 'maintain_name' ] = null; 
			$data[ 'building' ] = null; 
			$data[ 'branding_status' ] = '';
			$data[ 'full_branding' ] = '';
			$data[ 'contract_end' ] = '';
			$data[ 'value' ] = '';
			$data[ 'owner_name' ] = '';
			$data[ 'owner_gender' ] = '';
			$data[ 'owner_birth_place' ] = '';
			$data[ 'owner_birth_date' ] = '';
			$data[ 'owner_religion' ] = '';
			$data[ 'owner_email' ] = '';
			$data[ 'owner_phone' ] = '';
			$data[ 'owner_identity_type' ] = '';
			$data[ 'owner_identity_number' ] = '';
			$data[ 'outbond' ] = '';
			$data[ 'outlet_id' ] = '';
			$data[ 'outlet_status' ] = '';
			$data[ 'outlet_type' ] = '';
			$data[ 'outlet_size' ] = '';
			$data[ 'outlet_location' ] = '';
			$data[ 'outlet_employee_number' ] = '';
			$data[ 'outlet_lifetime' ] = '';
			$data[ 'outlet_ownership' ] = '';
			$data[ 'outlet_smart_no' ] = '';
			$data[ 'outlet_business_focus' ] = '';
			$data[ 'outlet_customer_type' ] = '';
			$data[ 'outlet_size_of_business' ] = '';
			$data[ 'outlet_expansion_package' ] = '';
			$data[ 'outlet_join_lajang' ] = '';
			$data[ 'outlet_lajang_package' ] = '';
			$data[ 'outlet_lajang_is_reorder' ] = '';
			$data[ 'outlet_address' ] = '';
			$data[ 'outlet_name' ] = '';
			$data[ 'outlet_city' ] = '';
			$data[ 'outlet_province' ] = '';
			$data[ 'outlet_post_code' ] = '';
			$data[ 'outlet_phone' ] = '';
			$data[ 'outlet_eload_number' ] = '';
			$data[ 'outlet_business_structure' ] = '';
		}
		else if( $name == "bank" )
		{
			$data[ 'bank_name' ] = '';
			$data[ 'bank_branch' ] = '';
			$data[ 'bank_account_name' ] = '';
			$data[ 'bank_account_number' ] = '';
		}
		else
		{
			$data[ 'front_type' ] = '';
			$data[ 'front_name' ] = '';
			$data[ 'front_birth_place' ] = '';
			$data[ 'front_birth_date' ] = '';
			$data[ 'front_identity_type' ] = '';
			$data[ 'front_identity_no' ] = '';
			$data[ 'front_religion' ] = '';
			$data[ 'front_work' ] = '';
			$data[ 'front_marital' ] = '';
			$data[ 'front_address' ] = '';
			$data[ 'front_city' ] = '';
			$data[ 'front_province' ] = '';
			$data[ 'front_zip' ] = '';
			$data[ 'front_mdn' ] = '';
			$data[ 'front_remark' ] = '';
		}
		
		return $data;
	}
	
	private function fillData( $arr, $type )
	{		
		foreach( $arr as $combo )
		{
			$query = $this->mmaster->getComboData( $combo );
			$i = 0;
			foreach( $query->result() as $r )
			{
				$data[ 'data' ][ $combo ][ 'member_value' ][ $i ] = $r->member_value;
				$data[ 'data' ][ $combo ][ 'member_display' ][ $i ] = $r->member_display;
				$i++;
			}
		}
		
		/**************************** ISI COMBO PROVINCE *****************************/
		$query = $this->mmaster->getRecord( 't_mtr_province' );
		$i = 0;
		foreach( $query->result() as $r )
		{
			$data[ 'data' ][ 'province' ][ 'member_value' ][ $i ] = $r->province_id;
			$data[ 'data' ][ 'province' ][ 'member_display' ][ $i ] = $r->province_name;
			$i++;
		}
				
		/*******************************ISI TERRITORY PATH******************************/
		$result = $this->mmaster->getTerritoryPath( $this->session->userdata( 'username' ), 'cluster' );
		$data[ 'data' ][ 'tr_path' ][ 'member_display' ] = $result[ 'path' ];
		$data[ 'data' ][ 'tr_path' ][ 'member_value' ] = $result[ 'territory_id' ];
		
		
		/************* ISI COMBO FIELD NAME PADA MAINTAINED BY *************************/
		$query = $this->mmaster->getMaintainName( '', $type );
		$i = 0;
      //  print_r($query);return;
		if( $query != null )
		{
			foreach( $query->result() as $r )
			{
				$data[ 'data' ][ 'maintain_name' ][ 'member_display' ][ $i ] = $r->user_name;
				$data[ 'data' ][ 'maintain_name' ][ 'member_value' ][ $i ] = $r->user_id;
				$data[ 'data' ][ 'maintain_name' ][ 'pos' ][ $i ] = $this->mmaster->getPosition( $r->user_id )->row()->user_group_name;
				$i++;
			}
		}
		else
		{
			$data[ 'data' ][ 'maintain_name' ][ 'member_display' ][ $i ] = '';
			$data[ 'data' ][ 'maintain_name' ][ 'member_value' ][ $i ] = '';
			$data[ 'data' ][ 'maintain_name' ][ 'pos' ][ $i ] = '';				
		}
		return $data;
	}
	

    function approval($proses="", $id="") {
        $data['template'] = "shell/smooth";
        $data['users'] = $this->mmaster->getAgents();
        $data['main_view'] = 'f-agents';
        $data['proses'] = $proses;
        $data['id'] = $id;
        
        $data['data'] = array("name" => "", "address" => "", "teritory_id" => "");
        if ($proses <> "" && $id <> "") {
            $getdata = $this->mmaster->getAgents($id);
            foreach ($getdata as $r) {
                $data['data']['name'] = $r->agent_name;
                $data['data']['address'] = $r->address;
                $data['data']['teritory_id'] = $r->teritory_id;
            }
        }

        #inisialisasi elemen form yang harus diisi
        $this->form_validation->set_rules('name', 'Nama', 'required');
        $this->form_validation->set_rules('address', 'Alamat', 'required');
        $this->form_validation->set_rules('teritory_id', 'Territory', 'required');
        $this->form_validation->set_rules('agent_type', 'Tipe Agen', 'required');
        $this->form_validation->set_rules('agent_selling_type', 'Tipe Penjualan', 'required');
        //$this->form_validation->set_error_delimiters('<li>', '</li>');
        //$this->form_validation->set_message('required', 'Kolom <b>%s</b> harus diisi.');

        if ($this->form_validation->run() != FALSE) {
            // masukkan data di sini
            $this->mmaster->saveAgents($id);
            $this->session->set_flashdata('message', 'Data Berhasil dimasukkan');
            redirect(base_url() . "index.php/agents/approval");
        }
        $hasil = "";
        //Donnie
        //Check for agent status
        $this->load->model('Magents');

        if ($proses == "agent_status_new") {
            $this->session->set_userdata('agent_status', 0);
        } else if ($proses == "agent_status_edited") {
            $this->session->set_userdata('agent_status', 2);
        } else if ($proses == "agent_status_registered") {
            $this->session->set_userdata('agent_status', 1);
        } else {
            $this->session->set_userdata('agent_status', 0);
        }

        $prosesSplitted = preg_split('/:/', $proses);
        if (sizeof($prosesSplitted) > 0) {

            if ($prosesSplitted[0] == "update_agent_status_new") {
                $this->Magents->updateAgentStatusById(1, $prosesSplitted[1], 0);
                $this->session->set_userdata('message', 'Agent approved.');
                $this->session->set_userdata('agent_status', 0);
            } else if ($prosesSplitted[0] == "update_agent_status_edited") {
                $this->Magents->updateAgentStatusById(1, $prosesSplitted[1], 2);
                $this->session->set_userdata('message', 'Agent approved.');
                $this->session->set_userdata('agent_status', 2);
            } else if ($prosesSplitted[0] == "update_agent_status_registered") {
                $this->Magents->updateAgentStatusById(0, $prosesSplitted[1], 1);
                $this->session->set_userdata('message', 'Agent approved.');
                $this->session->set_userdata('agent_status', 1);
            }
        }
        //
        $this->load->view($data['template'], $data);
    }
    
    function checkAgentId($agent_id){
       $this->Magents->checkAgentId($agent_id);
    }
    
    function checkUserRole(){
        return $this->Magents->checkUserRole(56);
    }

}